# -*- coding: utf-8 -*-

from PyQt4                  import QtCore, QtGui
from UI.UI_more_custom      import Ui_more_widget
from utils.utils            import getIconsDirectory
from utils.utils            import getIconPathFromExe
from constants.constants    import TABLE_LAUNCH_CONFIGURATIONS
from constants.constants    import TABLE_ACTION_LAUNCH_REL
from constants.constants    import TABLE_NAME_CONFIGURATIONS
from constants.constants    import ICON_NO_IMAGE
from utils.utils            import setTheme
from launch_config_dial     import LaunchConfigDial
import os
import logging

class MoreConfigWidget(Ui_more_widget, QtGui.QWidget):
    def __init__(self, dbInst=None, exeList=[], parent=None):
        super(MoreConfigWidget, self).__init__(parent)
        self.dbInst     = dbInst
        self.exeList    = exeList
        self.parentMainForm = parent
        self.setupUi(self)
        self.populateMoreWidget()
        self.setEvents()
        self.initFields()

    def initFields(self):
        confObjects = self.dbInst.getRowsTable(TABLE_NAME_CONFIGURATIONS, fields=['config_name', 'config_value'], filtersList=[('config_name', '=', 'BROWSER_SITES_ROWS')])
        confVal = 0
        if confObjects[0].config_value:
            confVal = confObjects[0].config_value
        self.tableWidget_browser.setRowCount(int(confVal))
        self.tableWidget_browser.setHorizontalHeaderLabels(['Browser Name'])
        self.menuObj = None
        self.launchExeList = []
        self.saveMultipleLaunchDict = {}
        self.tableWidget_browser.horizontalHeader().setResizeMode(QtGui.QHeaderView.ResizeToContents)

    def launchConfigDial(self):
        dial = LaunchConfigDial(self, self.dbInst, self.menuObj, self.exeList)
        #dial.showMaximized()
        if dial.exec_() == QtGui.QDialog.Accepted:
            self.saveMultipleLaunchDict[self.menuObj] = dial.outObjects
            self.updateLaunchLocalTable(dial)

    def updateLaunchLocalTable(self, dial):
        self.listWidgetConfigurations.setAlternatingRowColors(True)
        self.listWidgetConfigurations.clear()
        for rowCount in range(0, dial.tableWidget_local.rowCount()):
            conIndex = dial.config_headers_order.index('exe_path')
            exePath = dial.tableWidget_local.item(rowCount, conIndex).text()
            self.addItemToTable(exePath)
            
    def addItemToTable(self, text):
        self.launchExeList.append(unicode(text))
        iconPath = getIconPathFromExe(text)
        iconObj = QtGui.QIcon(iconPath)
        listWidgetItem = QtGui.QListWidgetItem(iconObj,text)
        self.listWidgetConfigurations.addItem(listWidgetItem) 
                    
    def populateMoreWidget(self, menuObj=False):
        setTheme(self)
        if menuObj:
            self.menuObj = menuObj
            self.label.setText('Menu Name')
            self.lineEdit.setText(menuObj.menu_name)
            self.label_1.setText('Tooltip')
            self.textEdit.setText(menuObj.tooltip)
            self.label_exe_path.setText('Exe Path')
            self.lineEdit_exe_path.setText(menuObj.exe_file_path)
            self.label_icon_path.setText('Icon Path')
            self.lineEdit_icon_path.setText(menuObj.menu_icon_path)
            self.label_4.setText('Menu Type')
            self.lineEdit_4.setText(menuObj.type)
            self.lineEdit_4.setReadOnly(True)
            self.lineEdit_4.setDisabled(True)
            self.label_5.setText('Sequence')
            self.spinBox_sequence.setValue(int(menuObj.sequence))
            self.checkBox_hidden.setChecked(eval(str(menuObj.hide)))
            self.pushButton_exe_path.setText('...')
            self.pushButton_icon_path.setText('...')
            self.setFieldsHidden(menuObj)
            self.setImageFromPath(menuObj.menu_icon_path, menuObj.exe_file_path)
            self.populateLocalConfigs()
            self.populateBrowserConfigs(menuObj)
            self.lineEdit_folder.setText(unicode(menuObj.folder_path))
            self.lineEdit_cmd.setText(menuObj.cmd_path)
            
            if eval(str(menuObj.use_configurations)):
                self.radioButton_launch_config.setChecked(True)
                self.tableWidget_browser.setHidden(True)
                self.listWidgetConfigurations.setHidden(False)
                self.lineEdit_folder.setHidden(True)
                self.label_folder_path.setHidden(True)
                self.pushButton_folder.setHidden(True)
                self.label_exe_path.setHidden(True)
                self.lineEdit_exe_path.setHidden(True)
                self.pushButton_exe_path.setHidden(True)
                self.label_cmd.setHidden(True)
                self.lineEdit_cmd.setHidden(True)
                self.radioButton_cmd.setHidden(True)
            elif eval(str(menuObj.use_browser)):
                self.radioButton_browser.setChecked(True)
                self.tableWidget_browser.setHidden(False)
                self.listWidgetConfigurations.setHidden(True)
                self.lineEdit_folder.setHidden(True)
                self.label_folder_path.setHidden(True)
                self.pushButton_folder.setHidden(True)
                self.label_cmd.setHidden(True)
                self.lineEdit_cmd.setHidden(True)
                self.radioButton_cmd.setHidden(True)
            elif eval(str(menuObj.use_folder)):
                self.radioButton_folder.setChecked(True)
                self.tableWidget_browser.setHidden(True)
                self.listWidgetConfigurations.setHidden(True)
                self.lineEdit_folder.setHidden(False)
                self.label_folder_path.setHidden(False)
                self.pushButton_folder.setHidden(False)
                self.label_exe_path.setHidden(True)
                self.lineEdit_exe_path.setHidden(True)
                self.pushButton_exe_path.setHidden(True)
                self.label_cmd.setHidden(True)
                self.lineEdit_cmd.setHidden(True)
                self.radioButton_cmd.setHidden(True)
            elif eval(str(menuObj.use_cmd)):
                self.radioButton_cmd.setChecked(True)
                self.label_cmd.setHidden(False)
                self.lineEdit_cmd.setHidden(False)
                self.radioButton_cmd.setHidden(False)
                self.tableWidget_browser.setHidden(True)
                self.listWidgetConfigurations.setHidden(True)
                self.lineEdit_folder.setHidden(True)
                self.label_folder_path.setHidden(True)
                self.pushButton_folder.setHidden(True)
                self.label_exe_path.setHidden(True)
                self.lineEdit_exe_path.setHidden(True)
                self.pushButton_exe_path.setHidden(True)
            else:
                self.radioButton_single_launch.setChecked(True)
                self.tableWidget_browser.setHidden(True)
                self.listWidgetConfigurations.setHidden(True)
                self.lineEdit_folder.setHidden(True)
                self.label_folder_path.setHidden(True)
                self.pushButton_folder.setHidden(True)
                self.label_configurations.setHidden(True)
                self.label_cmd.setHidden(True)
                self.lineEdit_cmd.setHidden(True)
            if menuObj.type.upper() == 'MENU':
                self.radioButton_browser.setHidden(True)
                self.radioButton_folder.setHidden(True)
                self.radioButton_launch_config.setHidden(True)
                self.radioButton_single_launch.setHidden(True)
                self.radioButton_cmd.setHidden(True)
                self.lineEdit_cmd.setHidden(True)
                self.label_cmd.setHidden(True)
            else:
                self.radioButton_browser.setHidden(False)
                self.radioButton_folder.setHidden(False)
                self.radioButton_launch_config.setHidden(False)
                self.radioButton_single_launch.setHidden(False)
                self.radioButton_cmd.setHidden(False)
            self.show()
        else:
            self.menuObj = None
            self.hide()

    def populateBrowserConfigs(self, menuObj):
        # Clean items
        #print 'here %s  %s' % (menuObj.menu_name, menuObj.browser_sites)
        siteRows = menuObj.browser_sites
        browserSiteRows = len(siteRows)
        colCount = self.tableWidget_browser.columnCount()
        for rowCount in range(self.tableWidget_browser.rowCount()):
            valueToSet = ''
            if rowCount+1 <= browserSiteRows:
                siteObj = siteRows[rowCount]
                valueToSet = siteObj.name
            tableItem = QtGui.QTableWidgetItem(valueToSet)
            self.tableWidget_browser.setItem(rowCount, colCount-1, tableItem)

    def populateLocalConfigs(self):
        self.launchExeList = []
        avaibleRelations    = self.dbInst.getRowsTable(TABLE_ACTION_LAUNCH_REL,[],[('act_id','=',self.menuObj.id)])
        self.listWidgetConfigurations.clear()
        for relationObj in avaibleRelations:
            rowsTable = self.dbInst.getRowsTable(TABLE_LAUNCH_CONFIGURATIONS,[],[('id','=',relationObj.launch_id)])
            if rowsTable:
                exePath = rowsTable[0].exe_path
                self.launchExeList.append(unicode(exePath))
                self.addItemToTable(exePath)
        
    def setImageFromPath(self, iconPath, exe_file_path=''):
        iconPath = unicode(iconPath)
        exe_file_path = unicode(exe_file_path)
        iconsDir = getIconsDirectory()
        iconDefaultPath = os.path.join(iconsDir, ICON_NO_IMAGE)
        def noImage():
            iconPath = ''

            if os.path.exists(iconDefaultPath):
                iconPath = iconDefaultPath
            else:
                logging.warning('Icons default path: %s not exists'%(iconDefaultPath))
            return unicode(iconPath)
        noImagePath = noImage()
        if iconPath != noImagePath:
            self.setIcon(iconPath)
            self.lineEdit_icon_path.setText(iconPath)
            return 
        exeExist = os.path.exists(exe_file_path)
        if not exe_file_path or not exeExist:
            iconPath = noImage()
        elif exeExist:
            iconPath = getIconPathFromExe(exe_file_path)
            if not iconPath:
                iconPath = noImage()
        self.setIcon(iconPath)
        self.lineEdit_icon_path.setText(iconPath)
        
    def setIcon(self, iconPath):
        if iconPath:
            #self.lineEdit_icon_path.setText(iconPath)
            pixmap = QtGui.QPixmap(iconPath)
            self.label_image.setFixedWidth(75)
            self.label_image.setFixedHeight(75)
            labelHeight = self.label_image.height()
            labelWidth = self.label_image.width()
            pixmap = pixmap.scaled(labelWidth, 
                                     labelHeight, 
                                     aspectRatioMode=QtCore.Qt.IgnoreAspectRatio, 
                                     transformMode=QtCore.Qt.FastTransformation)
            self.label_image.setPixmap(pixmap)
        
    def setFieldsHidden(self, menuObj):
        if menuObj.type == 'menu':
            self.label_exe_path.setHidden(True)
            self.lineEdit_exe_path.setHidden(True)
            self.pushButton_exe_path.setHidden(True)
            self.pushButton_configurations.setHidden(True)
            self.listWidgetConfigurations.setHidden(True)
        elif menuObj.type == 'action':
            self.label_exe_path.setHidden(False)
            self.lineEdit_exe_path.setHidden(False)
            self.pushButton_exe_path.setHidden(False)
            self.pushButton_configurations.setHidden(False)
            if eval(str(menuObj.use_configurations)):
                self.listWidgetConfigurations.setHidden(False)
                self.label_configurations.setHidden(False)
                self.pushButton_configurations.setHidden(False)
            else:
                self.listWidgetConfigurations.setHidden(True)
                self.label_configurations.setHidden(True)
                self.pushButton_configurations.setHidden(True)
            
    def setEvents(self):
        self.pushButton_configurations.clicked.connect(self.launchConfigDial)
        self.lineEdit_folder.editingFinished.connect(self.leFolderEdited)
        self.lineEdit_exe_path.editingFinished.connect(self.leExePathEdited)
        
    def leFolderEdited(self):
        selectedMenu = self.parentMainForm.getSelectedMenu()
        if selectedMenu:
            folderPath = self.lineEdit_folder.text()
            selectedMenu.folder_path = unicode(folderPath)
            actionName = self.lineEdit.text()
            if not actionName:
                fileBaseName = os.path.basename(str(folderPath))
                fileName = fileBaseName.split('.')[0]
                self.lineEdit.setText(fileName)

    def leExePathEdited(self):
        exePath = self.lineEdit_exe_path.text()
        self.parentMainForm.setExePath(exePath)
